package com.ng.biz.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ng.biz.model.domain.Disk;
import com.ng.biz.service.IDisk;
import com.ng.common.model.response.R;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.Result;
import io.minio.messages.Item;

@Service
public class DiskImpl implements IDisk{
	
	@Value("${minio.bucket-name}")
	private String bucketName;
	
	@Autowired
	private  MinioClient minioClient;

	@Override
	public  R<String> deleteByIds(String ids) {
		String[] arr = ids.split(",");
		if (arr == null || arr.length <= 0) {
			return R.failed("请选择需要删除的文件/文件夹.");
		}
		for (String id : arr) {
			// 1. 先获取文件信息
			Disk disk = Disk.dao.findById(id);
			if (disk == null) {
				continue;
			}
			try {
				delete(disk);
			}catch (Exception e) {
				return R.failed("删除文件失败: " + e.getMessage());
			}
		}
		return R.ok("删除成功.");
	}
	
	private void deleteChildrens(String id) throws Exception {
		List<Disk> list=Disk.dao.find("select * from "+Disk.TABLE_NAME+" where parent_id=?",id);
		for(Disk disk:list) {
			delete(disk);
		}
	}
	
	private void delete(Disk disk) throws Exception {
		try {
			// 2. 如果是文件夹，需要递归删除所有子文件
			if ("folder".equals(disk.getType())) {
				deleteChildrens(disk.getId());
				// 列出文件夹下所有对象
				Iterable<Result<Item>> results = minioClient.listObjects(
					ListObjectsArgs.builder()
						.bucket(bucketName)
						.prefix(disk.getPath() + "/")
						.recursive(true)
						.build()
				);
				
				// 删除文件夹下所有文件
				for (Result<Item> result : results) {
					Item item = result.get();
					minioClient.removeObject(
						RemoveObjectArgs.builder()
							.bucket(bucketName)
							.object(item.objectName())
							.build()
					);
				}
			} else {
				// 3. 如果是文件，直接删除
				minioClient.removeObject(
					RemoveObjectArgs.builder()
						.bucket(bucketName)
						.object(disk.getPath())
						.build()
				);
			}
			disk.delete();
		}catch (Exception e) {
			throw  e;
		}
	}

}
